import React from 'react';
import { connect } from "react-redux";
import Topic from "./components/Topic";
import List from "./components/List";
import Recommend from "./components/Recommend";
import Writer from "./components/Writer";
import Test from "./components/Test";
import { actionCreator } from "./store";

import {
  HomeWrapper,
  HomeLeft,
  HomeRight,
  BackTop
} from "./style";

class Home extends React.PureComponent {
  handleScrollTop() {
    window.scrollTo(0, 0);
  }

  render() {
    const { showBackTop } = this.props;
    return (
      <HomeWrapper>
        <HomeLeft>
          <Test></Test>
          <Topic></Topic>
          <List></List>
        </HomeLeft>
        <HomeRight>
          <Recommend></Recommend>
          <Writer></Writer>
        </HomeRight>
        {showBackTop ? <BackTop onClick={this.handleScrollTop}>回到顶部</BackTop> : null}
      </HomeWrapper>
    );
  }

  componentDidMount() {
    const { changeHomeData } = this.props;
    changeHomeData();
    this.bindEvents();
  }

  componentWillUnmount() {
    const { changeBackTopShow } = this.props;
    window.removeEventListener('scroll', changeBackTopShow)
  }

  // 在组件挂载时添加监听事件，记得也要在组件卸载时移除监听事件
  bindEvents() {
    const { changeBackTopShow } = this.props;
    window.addEventListener('scroll', changeBackTopShow)
  }
}

const mapState = (state) => {
  return {
    showBackTop: state.getIn(['home', 'showBackTop'])
  }
}

const mapDispatch = (dispatch) => {
  return {
    changeHomeData() {
      dispatch(actionCreator.getHomeInfo());
    },
    changeBackTopShow() {
      if(document.documentElement.scrollTop > 480) {
        dispatch(actionCreator.changeBackTopShow(true))
      } else {
        dispatch(actionCreator.changeBackTopShow(false))
      }
    }
  }
}
 
export default connect(mapState, mapDispatch)(Home);